var BaseFun = require('./Function'),
    BaseConst = require("./Const"),
    http = require('http');

//请求代理服务
exports.requestProxy = function(req, res){
    if(!BaseConst.Intranet){
        var newErr = new Error();
        newErr.leval = 5;
        newErr.title = '请求失败';
        newErr.message = '没有配置内部服务器地址';
        BaseFun.responseFun(res, newErr);
        return;
    }

    var contentType = req.headers["content-type"];
    var contentLength = req.headers["content-length"];

    var reqData = JSON.stringify(req.body);
    var options = {
        host: req.headers['host'],
        hostname: BaseConst.Intranet.HostName,
        port: BaseConst.Intranet.Port,
        path: req.url,
        method: req.method,
        headers: req.headers
         // {
         //      'Content-Type': contentType,
         //      'Content-Length': contentLength
         // }
    };

    delete options.headers["accept-encoding"];
    delete options.headers.connection;

    var httpRequest = http.request(options, function (httpResponse) {
        httpResponse.setEncoding('utf-8');
        httpResponse.on('data', function(data){
            //根据 angular.js function fromJson(json) 解析字符串
            data = data.replace(/^\)\]\}',?\n/, '').trim();
            data = JSON.parse(data);
            if(data.Error){
                BaseFun.responseFun(res, data.Error);
            }
            else{
                BaseFun.responseFun(res, null, data.Data);
            }
        });

        httpResponse.on('end', function(){
            //res.end();
        });
    });

    httpRequest.on('error', function (err) {
        var newErr = new Error();
        newErr.leval = 5;
        newErr.title = '请求失败';
        newErr.message = err.message;
        BaseFun.responseFun(res, newErr);
    });

    //httpRequest.setTimeout(10*1000, function(){
    //    var newErr = new Error();
    //    newErr.leval = 5;
    //    newErr.title = '请求失败';
    //    newErr.message = '代理服务器请求超时';
    //    BaseFun.responseFun(res, newErr);
    //});
    httpRequest.write(reqData);
    httpRequest.end();
};
